//
//  String+SubString.swift
//  Swaddle
//
//  Created by memory on 2021/5/17.
//

import Foundation
// MARK: - 字符串截取
public extension YLDevelop where Base == String{
    /// String使用下标截取字符串
    /// string[index] 例如："abcdefg"[3] // c
    subscript (i:Int)->String{
        let startIndex = base.index(base.startIndex, offsetBy: i)
        let endIndex = base.index(startIndex, offsetBy: 1)
        return String(base[startIndex..<endIndex])
    }
    /// String使用下标截取字符串
    /// string[index..<index] 例如："abcdefg"[3..<4] // d
    subscript (r: Range<Int>) -> String {
        get {
            let startIndex = base.index(base.startIndex, offsetBy: r.lowerBound)
            let endIndex = base.index(base.startIndex, offsetBy: r.upperBound)
            return String(base[startIndex..<endIndex])
        }
    }
    /// String使用下标截取字符串
    /// string[index,length] 例如："abcdefg"[3,2] // de
    subscript (index:Int , length:Int) -> String {
        get {
            let startIndex = base.index(base.startIndex, offsetBy: index)
            let endIndex = base.index(startIndex, offsetBy: length)
            return String(base[startIndex..<endIndex])
        }
    }
    /// 截取 从头到i位置
    /// 例如："abcdefg".substring(to:3) // abc
    func substring(to:Int) -> String{
        return self[0..<to]
    }
    /// 截取 从i位置结尾
    /// 例如："abcdefg".substring(from:3) // defg
    func substring(from:Int) -> String{
        return self[from..<base.count]
    }
}
